/*
 *  Copyright (c)  2016-NOW  Jacars Co.Ltd.
 *  All rights reserved.
 */
package com.jacars.biz.user.dao.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jacars.biz.user.dao.mapper.JsptDictMapper;
import com.jacars.biz.user.dao.model.JsptDict;
import com.jacars.biz.user.dao.service.JsptDictService;
import com.jacars.biz.user.vo.JsptDictVO;
import com.jacars.common.service.impl.SuperServiceImpl;
import com.jacars.common.utils.FuncUtil;
import com.jacars.common.utils.StringPool;
import com.jacars.common.utils.node.ForestNodeMerger;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.jacars.biz.user.cache.CacheNames.DICT_LIST;
import static com.jacars.biz.user.cache.CacheNames.DICT_VALUE;


/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
public class JsptDictServiceImpl extends SuperServiceImpl<JsptDictMapper, JsptDict> implements JsptDictService {

	@Override
	public IPage<JsptDictVO> selectDictPage(IPage<JsptDictVO> page, JsptDictVO dict) {
		return page.setRecords(baseMapper.selectDictPage(page, dict));
	}

	@Override
	public List<JsptDictVO> tree() {
		return ForestNodeMerger.merge(baseMapper.tree());
	}

	@Override
	@Cacheable(cacheNames = DICT_VALUE, key = "#code+'_'+#dictKey")
	public String getValue(String code, Integer dictKey) {
		return FuncUtil.toStr(baseMapper.getValue(code, dictKey), StringPool.EMPTY);
	}

	@Override
	@Cacheable(cacheNames = DICT_LIST, key = "#code")
	public List<JsptDict> getList(String code) {
		return baseMapper.getList(code);
	}

	@Override
	@CacheEvict(cacheNames = {DICT_LIST, DICT_VALUE}, allEntries = true)
	public boolean submit(JsptDict dict) {
		LambdaQueryWrapper<JsptDict> lqw = Wrappers.<JsptDict>query().lambda().eq(JsptDict::getCode, dict.getCode()).eq(JsptDict::getDictKey, dict.getDictKey());
		Long cnt = baseMapper.selectCount((FuncUtil.isEmpty(dict.getId())) ? lqw : lqw.notIn(JsptDict::getId, dict.getId()));
		if (cnt > 0) {
			throw new RuntimeException("当前字典键值已存在!");
		}

		return saveOrUpdate(dict);
	}
}
